import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueCookies from 'vue-cookies'

Vue.use(VueCookies);
Vue.config.productionTip = false
import axios from 'axios'
import VueAxios from 'vue-axios'
import ElementUI, {Message, MessageBox} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

axios.defaults.baseURL = 'http://localhost:9999/';//发送axios请求时自动拼接前缀

let baseUrl = 'http://localhost:9999/';
Vue.prototype.$baseURL = baseUrl;//声明的系统变量

Vue.use(ElementUI);
Vue.use(VueAxios, axios)



//axios请求拦截器
axios.interceptors.request.use(function (config) {

    var token = $cookies.get("token")  // 在发送请求之前获取token
    if (token) {
        config.headers.token = token  //把token放入请求头
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    //console.log(response.data)
    console.log("====>" + response.data.msg)
    if (response.data.code == 401 || response.data.code == 403) {
        Message.warning("认证失败请重新登录")
        router.push("/login")
    }
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});



//动态添加路由-导航守卫
router.beforeEach((to, from, next) => {

    if (to.path != '/login') {
        let indexChildrenRouters = [];
        axios.get(baseUrl + 'menu/list').then(res => {
            if (res.data.code == 200) {
                let menuData = res.data.data;
                menuData.forEach(menu => {
                        if (menu.hasOwnProperty("children")) {
                            let subMenuList = menu.children;
                            subMenuList.forEach(subMenu => {
                                let newRouter = {
                                    name: subMenu.name,
                                    path: subMenu.path
                                }
                                newRouter.component = () => import( './views/' + subMenu.component + '.vue');
                                indexChildrenRouters.push(newRouter);
                            })
                        }
                    }
                )
                router.options.routes[0].children = indexChildrenRouters;
                router.addRoutes(router.options.routes);
            }
        })

    }
    next();
})



new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
